<?php

class IndexController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
        $this->pageTitle = 'ShineTech-login';
        if (!Yii::app()->user->isGuest) {
            $this->redirect($this->createUrl('user/index'));
        }
        $login_model = new LoginForm();
        $this->performAjaxValidation($login_model, 'login_form');
        if (isset($_POST['LoginForm'])) {
            $login_model->attributes = $_POST['LoginForm'];
            if ($login_model->validate() && $login_model->login()) {
                $this->redirect($this->createUrl('user/index'));
            }
        }
		$this->render('login',array(
            'user_login' => $login_model,
        ));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

    protected function performAjaxValidation($model, $form_id)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === $form_id) {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}